<template>
    
    <div class="question-generator">
        <YHeader name="一键出题"></YHeader>
        <div class="content">
            <!-- 文件上传区域 -->
            <van-uploader
            v-model="fileList"
            :max-count="1"
            :before-read="beforeRead"
            :after-read="afterRead"
            >
            <van-button type="primary" icon="plus">选择文件</van-button>
            </van-uploader>
    
            <!-- 上传进度显示 -->
            <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-box">
                <van-progress
                    :percentage="uploadProgress"
                    :show-pivot="true"
                />
            </div>
    
            <!-- 生成的题目展示区域 -->
            <div class="questions-container" v-if="questions.length">
                <van-divider style="margin-left: 4%;">生成的题目：</van-divider>
                <van-cell-group inset>
                    <van-cell
                    v-for="(item, index) in questions"
                    :key="index"
                    class="question-cell"
                    >
                    <div class="question-item">
                        <!-- 题目序号和内容 -->
                        <div class="question-header">
                        <span class="question-number">{{ index + 1 }}.</span>
                        <span class="question-text">{{ item.question }}</span>
                        </div>
                        
                        <!-- 选项部分 -->
                        <div v-if="item.options" class="options-container">
                            <div 
                                v-for="(option, idx) in item.options" 
                                :key="idx" 
                                class="option-item"
                            >
                                <span class="option-label">{{ ['A', 'B', 'C', 'D'][idx] }}.</span>
                                <span class="option-content">{{ option }}</span>
                            </div>
                        </div>
                        <!-- 答案部分 -->
                        <div class="answer-section">
                            <van-button 
                                size="small" 
                                type="primary" 
                                plain
                                @click="toggleAnswer(index)"
                            >
                                {{ showAnswers[index] ? '隐藏答案' : '查看答案' }}
                            </van-button>
                        
                            <div v-show="showAnswers[index]" class="answer-content">
                                <van-tag type="primary" size="medium">答案</van-tag>
                                <div class="answer-text" v-if="item.options">
                                <span class="correct-answer">{{ ['A', 'B', 'C', 'D'][Number(item.correctAnswer)] }}</span>
                                </div>
                                <div class="answer-text" v-else>
                                    {{ item.answer }}
                                </div>
                                
                                <!-- 解析部分 -->
                                <template v-if="item.explanation">
                                <van-tag type="success" size="medium" class="explanation-tag">解析</van-tag>
                                <div class="explanation-text">
                                    {{ item.explanation }}
                                </div>
                                </template>
                            </div>
                        </div>
                    </div>
                    </van-cell>
                </van-cell-group>
            </div>
    
            <!-- 操作按钮 -->
            <div class="actions">
                <van-button
                    type="primary"
                    :disabled="!hasUploadedFile"
                    :loading="generating"
                    @click="generateQuestions"
                    block
                >
                    生成题目
                </van-button>
                <van-button 
                    plain 
                    block 
                    @click="resetAll"
                    style="margin-top: 10px;"
                >
                    重置
                </van-button>
            </div>
        </div>
    </div>
    
</template>
  
<script setup lang="ts">
  import { ref } from 'vue'
  import { showToast, showLoadingToast, closeToast } from 'vant'
  import YHeader from '@/components/YHeader.vue';
import { getGenerateProblem } from '@/api/code/codeCompletion';

  const fileList = ref([])
  const uploadProgress = ref(0)
  const hasUploadedFile = ref(false)
  const generating = ref(false)
  const questions = ref<Array<{
    question: string
    options?: string[]
    correctAnswer?: number
    answer?: string
    explanation?: string
  }>>([])
  const uploadedFile = ref<File | null>(null)
  // 添加答案显示状态控制
const showAnswers = ref<boolean[]>([])

// 切换答案显示状态
const toggleAnswer = (index: number) => {
  showAnswers.value[index] = !showAnswers.value[index]
}
  
  // 文件上传前的校验
  const beforeRead = (file: File) => {
    const allowedTypes = ['.txt', '.md', '.doc', '.docx', '.pdf', '.jpg', '.png', '.jpeg', '.gif']
    const fileName = file.name.toLowerCase()
    const isValidType = allowedTypes.some(type => fileName.endsWith(type))
    
    if (!isValidType) {
      showToast('请上传正确的文件格式')
      return false
    }
    
    return true
  }
  
  // 文件上传后的处理
  const afterRead = async (file) => {
    uploadProgress.value = 0
    try {
      // 模拟上传进度
      const timer = setInterval(() => {
        uploadProgress.value += 10
        if (uploadProgress.value >= 100) {
          clearInterval(timer)
          uploadedFile.value = file.file
          hasUploadedFile.value = true
          showToast('上传成功')
        }
      }, 100)
    } catch (error) {
      showToast('文件上传失败')
    }
  }
  
  // 生成题目
const generateQuestions = async () => {
    if (!uploadedFile.value) {
        showToast('请先上传文件')
        return
    }

    generating.value = true
    const toast = showLoadingToast({
        message: '正在生成题目...',
        forbidClick: true,
    })
  
    try {
      // 这里需要调用后端API来处理文件并生成题目
      // const formData = new FormData()
      // formData.append('file', uploadedFile.value)
      // const response = await fetch('/api/generate-questions', {
      //   method: 'POST',
      //   body: formData
      // })
      // const data = await response.json()
      // questions.value = data.questions
  
        // 模拟数据，实际使用时请替换为真实API调用
        await new Promise(resolve => setTimeout(resolve, 20000))

        //const data = await getGenerateProblem(uploadedFile.value)
        //console.log(data)
        questions.value = [
        // {
        //     question: '示例题目1：这是一道自动生成的选择题？',
        //     options: ['选项A', '选项B', '选项C', '选项D'],
        //     correctAnswer: 1, // 对应选项B
        //     explanation: '这是问题的详细解析，说明为什么选B是正确答案。'
        // },
        {
            question: '`tablespace_definition_cache`的默认值是什么？',
            answer: '`tablespace_definition_cache`的默认值是256。',
            // explanation: '这里是简答题答案的补充解释。'
        },
        {
            question: '该变量的最小值和最大值分别是多少？',
            answer: '该变量的最小值是256，最大值是524288。',
            // explanation: '这里是简答题答案的补充解释。'
        },
        {
            question: '如果将`tablespace_definition_cache`设置为0，会有什么效果？',
            answer: '如果将`tablespace_definition_cache`设置为0，表示表空间定义对象仅在使用时才保留在字典对象缓存中。',
            // explanation: '这里是简答题答案的补充解释。'
        },
        ]
        // 初始化答案显示状态数组
        showAnswers.value = new Array(questions.value.length).fill(false)
    } catch (error) {
      showToast('生成题目失败')
    } finally {
      generating.value = false
      closeToast(toast)
    }
  }
  
    // 重置函数也需要更新
    const resetAll = () => {
        hasUploadedFile.value = false
        questions.value = []
        uploadedFile.value = null
        fileList.value = []
        uploadProgress.value = 0
        showAnswers.value = []
    }
</script>
  
<style scoped>
.question-generator {
margin-top: 2%;
height: 80%;
min-height: 100vh;
background-color: #f7f8fa;
}

.content {
padding: 16px;
}

.progress-box {
margin: 16px 0;
}

.questions-container {
margin-top: 16px;
}

.option-item {
margin: 8px 0;
color: #666;
font-size: 14px;
}

.actions {
margin-top: 24px;
padding: 0 16px 24px;
}

:deep(.van-cell-group) {
margin-top: 12px;
}

:deep(.van-uploader) {
padding: 16px;
width: 100%;
text-align: center;
background-color: #fff;
border-radius: 8px;
}

:deep(.van-uploader__wrapper) {
justify-content: center;
}

.question-cell {
padding: 16px;
}

.question-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.question-header {
  display: flex;
  gap: 8px;
}

.question-number {
  font-weight: bold;
  color: #1989fa;
  flex-shrink: 0;
}

.question-text {
  font-size: 15px;
  text-align: left;
  line-height: 1.5;
  color: #323233;
}

.options-container {
  padding-left: 24px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  display: flex;
  gap: 8px;
  font-size: 14px;
  line-height: 1.4;
}

.option-label {
  color: #1989fa;
  font-weight: 500;
  flex-shrink: 0;
}

.option-content {
  color: #646566;
}

:deep(.van-cell-group--inset) {
  margin: 0 12px;
}

:deep(.van-cell) {
  padding: 16px;
}

.answer-section {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.answer-content {
  margin-top: 8px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.answer-text {
  margin: 8px 0;
  text-align: left;
  color: #2c3e50;
  font-size: 14px;
  line-height: 1.5;
}

.correct-answer {
  font-weight: bold;
  color: #1989fa;
  font-size: 16px;
}

.explanation-tag {
  margin-top: 8px;
}

.explanation-text {
  margin-top: 4px;
  text-align: left;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.van-tag) {
  margin-right: 8px;
}

:deep(.van-button--small) {
  padding: 0 16px;
  height: 28px;
  align-self: flex-start;
}
</style>